<script setup>
import * as THREE from 'three';

const canvasContainer = ref(null);
// 1 创建场景
const scene = new THREE.Scene();

// 2 创建相机
const camera = new THREE.PerspectiveCamera(
    85,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
);
// 3 创建渲染器
const renderer = new THREE.WebGLRenderer({
  antialias: true,
  powerPreference: "high-performance", // 强制高性能模式
  failIfMajorPerformanceCaveat: false   // 允许性能折中方案
});


// 4 创建物体
const geometry = new THREE.BoxGeometry(1, 1, 1);
// 5 创建材质
const material = new THREE.MeshBasicMaterial({
  color: 0x00ff00,
  wireframe: true,
});
// 6 创建物体
const cube = new THREE.Mesh(geometry, material);

// 7 动画
const animate = function () {
  requestAnimationFrame(animate);
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
};
const init = () => {
  // 设置相机位置
  camera.position.z = 5;
  // 设置渲染器尺寸大小
  renderer.setSize(window.innerWidth, window.innerHeight);
  // 将渲染器添加到容器中
  canvasContainer.value.appendChild(renderer.domElement);
  // 添加物体到场景中
  scene.add(cube);
  // 渲染
  animate();
};

const resize = () => {
  window.addEventListener('resize', () => {
    // 更新摄像头
    camera.aspect = window.innerWidth / window.innerHeight;
    // 更新摄像头的投影矩阵
    camera.updateProjectionMatrix();
    // 更新渲染器
    renderer.setSize(window.innerWidth, window.innerHeight);
    // 设置渲染器的像素比
    renderer.setPixelRatio(window.devicePixelRatio);
  });
};


onMounted(() => {
  init();//初始化场景
  resize();//根据窗口变化，更新渲染器尺寸
});
onUnmounted(() => {
  if ( renderer ) {
    renderer.dispose();
    // 移除渲染器
    if ( canvasContainer.value && renderer.domElement ) {
      canvasContainer.value.removeChild(renderer.domElement);
    }
  }
});
</script>

<template>
  <div ref="canvasContainer" class="canvas-container"></div>
</template>

<style scoped>
.canvas-container {
  width: 100vw;
  height: 100vh; /* 改为视窗高度 */
  touch-action: none; /* 防止移动端滑动冲突 */
}
</style>